package com.zhongxi.guoyuan.view;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.libs.zxing.CaptureActivity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.zhongxi.guoyuan.OffLineShop.UI.PayMoneyActivity;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.personCenter.ClearWeedExchangeAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.UpdateResult;
import com.zhongxi.guoyuan.entity.ad.AdData;
import com.zhongxi.guoyuan.entity.ad.AdResult;
import com.zhongxi.guoyuan.entity.clearweed.ClearWeedGood;
import com.zhongxi.guoyuan.entity.clearweed.ClearWeedResult;
import com.zhongxi.guoyuan.entity.user.center.NewMessage;
import com.zhongxi.guoyuan.entity.user.center.UserExtendResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.LunBoUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.personalCenter.ClearWeedDetailActivity;
import com.zhongxi.guoyuan.view.personalCenter.ClearWeedSearchActivity;
import com.zhongxi.guoyuan.view.personalCenter.SystemMessageActivity;
import com.zhongxi.guoyuan.view.seller.SellerCenterActivity;
import com.zhongxi.guoyuan.view.seller.offline.AddParameter;
import com.zhongxi.guoyuan.view.shopCart.ShoppingCartActivity;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhongxi.guoyuan.widget.screenadaptaion.FitTextView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


public class MainHomeActivity extends BaseActivity implements View.OnClickListener, OnBannerListener, ClearWeedExchangeAdapter.OnItemClickListener, ViewTreeObserver.OnGlobalLayoutListener {

    private static final int MAINHOMEPAYMONEY = 88;
    private List<AdData> data = new ArrayList<AdData>();
    private LinearLayout meibiShop;
    private LinearLayout bolivarShop;
    private ImageView ivStroe;
    private String flag;

    private ImageView ivNewUser;
    private FrameLayout flow;
    /**
     * 分红点数
     */
    private RelativeLayout title;
    private LinearLayout llUpGift;
    private AlertDialog dialog;
    private Banner banner;
    private TextView tvAd;
    private LinearLayout ll_offline_shop;
    private ImageView trumpet;

    private AnimationDrawable animationDrawable;
    private TextView mTv_persion;

    private MyScrollView mMyScrollView;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager layoutManager;
    private ClearWeedExchangeAdapter adapter;
    private ClearWeedResult clearWeedResult;
    private List<ClearWeedGood> clearWeedGoodList = new ArrayList<>();
    private JSONObject storeInfo;
    private TextView tv_servicer;
    private ImageView iv_qr;
    private TextView tv_cart;
    private FitTextView etHomeSearch;
    private LinearLayout lienarMeasureHeight;
    private int stopMeasureHeight;
    private LinearLayout linearBody;
    private PopupWindow mPopupWindow;
    private int mHeight;

    private TextView tvTop1, tvTop2, tvTop3, tvTop4, tvTop5, tvTop6;
    private RelativeLayout homeTopSearch;
    private boolean noMore = false;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_main_home);
        title = (RelativeLayout) findViewById(R.id.title);
        mTv_persion = (TextView) findViewById(R.id.tv_persion);
        TextView tvShopTitle = (TextView) findViewById(R.id.tvShopTitle);
        tvShopTitle.setText(R.string.first);
        tv_servicer = (TextView) findViewById(R.id.tv_home_servicer);
        tvAd = (TextView) findViewById(R.id.tvAd);
        tvAd.requestFocus();


        ll_offline_shop = (LinearLayout) findViewById(R.id.ll_offline_shop);

        iv_qr = (ImageView) findViewById(R.id.iv_home_qr);
        trumpet = (ImageView) findViewById(R.id.trumpet_gif);

        llUpGift = (LinearLayout) findViewById(R.id.llUpGift);
        ivNewUser = (ImageView) findViewById(R.id.iv_home_newuser);
        //商城
        meibiShop = (LinearLayout) findViewById(R.id.meibiShop);
        bolivarShop = (LinearLayout) findViewById(R.id.bolivarShop);

        ivStroe = (ImageView) findViewById(R.id.iv_home_newstore);
        //设置高度
        flow = (FrameLayout) findViewById(R.id.flow);
        ImageUtils.setHeight(this, Constants.flowRate, flow);
        banner = (Banner) findViewById(R.id.banner);

        mMyScrollView = (MyScrollView) findViewById(R.id.sc_home_container);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_home_item);
        tv_cart = (TextView) findViewById(R.id.tv_cart);
        etHomeSearch = (FitTextView) findViewById(R.id.et_home_newSearchContent);

        lienarMeasureHeight = (LinearLayout) findViewById(R.id.lienar_mesureHeight);
        ViewTreeObserver mViewTreeObserver = lienarMeasureHeight.getViewTreeObserver();
        mViewTreeObserver.addOnGlobalLayoutListener(this);
        initRecycleview();

        initPopUpWindow();
    }

    private void initPopUpWindow() {
        View mView = LayoutInflater.from(this).inflate(R.layout.pop_home_layou, null);
        mPopupWindow = new PopupWindow(mView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        linearBody = (LinearLayout) mView.findViewById(R.id.linear_stopbody);
        tvTop1 = (TextView) mView.findViewById(R.id.home_bottom_tab1);
        tvTop2 = (TextView) mView.findViewById(R.id.home_bottom_tab2);
        tvTop3 = (TextView) mView.findViewById(R.id.home_bottom_tab3);
        tvTop4 = (TextView) mView.findViewById(R.id.home_bottom_tab4);
        tvTop5 = (TextView) mView.findViewById(R.id.home_bottom_tab5);
        tvTop6 = (TextView) mView.findViewById(R.id.home_bottom_tab6);
        homeTopSearch = (RelativeLayout) mView.findViewById(R.id.home_top_search);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tvTop2.setText(Html.fromHtml("<font color='#333'>线上赚</font><font color='#ff4c4c'>红豆<font>", Html.FROM_HTML_MODE_COMPACT));
        } else {
            tvTop2.setText(Html.fromHtml("<font color='#333'>线上赚</font><font color='#ff4c4c'>红豆<font>"));
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tvTop3.setText(Html.fromHtml("<font color='#333'>线下赚</font><font color='#ff7f00'>美豆<font>", Html.FROM_HTML_MODE_COMPACT));
        } else {
            tvTop3.setText(Html.fromHtml("<font color='#333'>线下赚</font><font color='#ff7f00'>美豆<font>"));
        }
        //测量弹窗的height
        int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        linearBody.measure(width, height);
        mHeight = linearBody.getMeasuredHeight();
        linearBody.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        tvTop1.setOnClickListener(this);
        tvTop2.setOnClickListener(this);
        tvTop3.setOnClickListener(this);
        tvTop4.setOnClickListener(this);
        tvTop5.setOnClickListener(this);
        tvTop6.setOnClickListener(this);
        homeTopSearch.setOnClickListener(this);


    }

    private void initRecycleview() {
        layoutManager = new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        mRecyclerView.setLayoutManager(layoutManager);
        adapter = new ClearWeedExchangeAdapter(this);
        mRecyclerView.setAdapter(adapter);

    }

    @Override
    protected void initData() {
        super.initData();
        unsubscribe();
        mDisposable = Observable.concat(AddParameter.getInstance().getAdData(1), AddParameter.getInstance().getNewMessage(),
                AddParameter.getInstance().upDataVersion())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showProgressDialog();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (o instanceof AdResult) {
                            MyApplication.getInstance().setSpValue(((AdResult) o).getSafeobj());
                            data.clear();
                            if (((AdResult) o).getCode() == 1) {
                                data.addAll(((AdResult) o).getData());
                                lunbo();
                            } else {
                                ToastUtil.show(getString(R.string.loseData, ((AdResult) o).getCode()));
                            }
                        } else if (o instanceof NewMessage) {
                            MyApplication.getInstance().setSpValue(((NewMessage) o).getSafeobj());
                            if (((NewMessage) o).getCode() == 1) {
                                if (null != ((NewMessage) o).getData().getDescription() && !"".equals(((NewMessage) o).getData().getDescription())) {
                                    String str = "";
                                    for (int i = 0; i < 5; i++) {
                                        str += ((NewMessage) o).getData().getTitle() + "                    ";
                                    }
                                    tvAd.setText(str);
                                    initAnimations();
                                }
                            } else {
                                ToastUtil.show(getString(R.string.loseData, ((NewMessage) o).getCode()));
                            }
                        } else if (o instanceof UpdateResult) {
                            MyApplication.getInstance().setSpValue(((UpdateResult) o).getSafeobj());
                            if (((UpdateResult) o).getCode() == 1) {
                                if (null != ((UpdateResult) o).getUpdClient() && !"".equals(((UpdateResult) o).getUpdClient())) {
                                    if (null != ((UpdateResult) o).getUpdClient().getDownUrl() && !"".equals(((UpdateResult) o).getUpdClient().getDownUrl())) {
                                        UpdateResult.UpdateData mUpdClient = ((UpdateResult) o).getUpdClient();
                                        downFile(mUpdClient.getDownUrl(), mUpdClient.getDesc());
                                    } else {
                                        isExists();
                                    }
                                } else {
                                    isExists();
                                }
                            } else {
                                ToastUtil.show(getString(R.string.loseData, ((NewMessage) o).getCode()));
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtil.show(UiUtils.getString(R.string.load_error));
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        getExchangedata();
                    }
                });
    }

    private void initAnimations() {
        animationDrawable = (AnimationDrawable) getResources().getDrawable(R.drawable.animation_trumpt);
        trumpet.setBackgroundDrawable(animationDrawable);
        animationStart();
    }

    private void animationStart() {
        if (animationDrawable != null && !animationDrawable.isRunning()) {
            animationDrawable.start();
        }
    }

    private void lunbo() {
        //初始化轮播控件
        banner.isAutoPlay(true);
        banner.setDelayTime(3000);
        banner.setIndicatorGravity(BannerConfig.CENTER);
        List<String> images = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            images.add(Url.IMG_URL + data.get(i).getImage());
        }
        banner.setImages(images)
                .setImageLoader(new GlideImageLoader())
                .start();

        banner.setOnBannerListener(this);
    }

    @Override
    public void OnBannerClick(int position) {
        if (!TextUtils.isEmpty(data.get(position).getId())) {
            LunBoUtils.getInstance(this).lunBoItemClickListener(data.get(position).getId(),
                    data.get(position).getIsvideo(), data.get(position).getUrl(), 3);
        }
    }

    /***
     * 豆豆兑换商品的点击事件
     * @param view
     * @param position
     */
    @Override
    public void onClick(View view, int position) {
        ClearWeedGood clearWeedGood = clearWeedGoodList.get(position);
        Intent intent = new Intent(MainHomeActivity.this, ClearWeedDetailActivity.class);
        intent.putExtra("id", clearWeedGood.getId());
        startActivity(intent);
    }

    /***
     * 计算悬停位置
     */
    @Override
    public void onGlobalLayout() {
        stopMeasureHeight = lienarMeasureHeight.getHeight();
        stopMeasureHeight -= mHeight;
        lienarMeasureHeight.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            //Glide 加载图片简单用法
            Glide.with(context).load(path).placeholder(R.mipmap.iv_loading).into(imageView);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    protected void onStop() {
        //结束轮播
        banner.stopAutoPlay();
        super.onStop();
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if (flag.equals("data")) {
                clearWeedResult = gson.fromJson(response, ClearWeedResult.class);
                MyApplication.getInstance().setSpValue(clearWeedResult.getSafeobj());
                if (pageNum == 1) {
                    clearWeedGoodList.clear();
                }
                if (clearWeedResult.getGoodsInfo() != null && clearWeedResult.getGoodsInfo().size() > 0) {
                    clearWeedGoodList.addAll(clearWeedResult.getGoodsInfo());
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        storeInfo = jsonObject.optJSONObject("store");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    adapter.setList(clearWeedGoodList, storeInfo);
                } else {
                    if (pageNum >= 2) {
                        adapter.setFooter_state(2);
                        noMore = true;
                    } else {
                        adapter.setFooter_state(0);
                    }
                    pageNum--;
                    if (pageNum < 1) {
                        pageNum = 1;
                    }
                }
                adapter.notifyDataSetChanged();
            } else if ("userinfo".equals(flag)) {
                UserExtendResult userExtendResult = gson.fromJson(response, UserExtendResult.class);
                MyApplication.getInstance().setSpValue(userExtendResult.getSafeobj());
                if (null != userExtendResult.getRedbean() && !"".equals(userExtendResult.getRedbean())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("hd", DataUtil.formatDataSixPoint(userExtendResult.getRedbean())).commit();
                }
                if (null != userExtendResult.getData() && !"".equals(userExtendResult.getData())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("inner", userExtendResult.getData().getInnercurrency()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("share", userExtendResult.getData().getSharesgains()).commit();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /***
     * 豆豆兑换列表
     */
    public void getExchangedata() {
        String longitude = MyApplication.getInstance().getLongitude();
        String latitude = MyApplication.getInstance().getLatitude();
        flag = "data";
        String str = "&page=" + pageNum + "&orderby=1" + "&cateid=0" + "&lng=" + longitude + "&lat=" + latitude;
        getServer(Url.CLEARWEED_GOODLIST, null, str, false, null, "get");
    }


    /**
     * 获取用户信息
     */
    private void getUserInfo() {
        flag = "userinfo";
        getServer(Url.MY_EXTEND_INFO, null, "", false, null, "get");
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
        } catch (Exception e) {
            e.getMessage();
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        meibiShop.setOnClickListener(this);
        bolivarShop.setOnClickListener(this);
        ivStroe.setOnClickListener(this);
        ivNewUser.setOnClickListener(this);
        tv_servicer.setOnClickListener(this);
        llUpGift.setOnClickListener(this);
        ll_offline_shop.setOnClickListener(this);
        tvAd.setOnClickListener(this);
        iv_qr.setOnClickListener(this);
        mTv_persion.setOnClickListener(this);
        tv_cart.setOnClickListener(this);
        adapter.setItemClickListener(this);
        etHomeSearch.setOnClickListener(this);

        ViewTreeObserver mViewTreeObserver = banner.getViewTreeObserver();
        mViewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                banner.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int bannerHeight = banner.getHeight();
            }
        });

        mMyScrollView.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {

                if (scrollY >= stopMeasureHeight) {

                    if (mPopupWindow != null && !mPopupWindow.isShowing()) {
                        mPopupWindow.showAsDropDown(title);
                    }
                } else {

                    if (mPopupWindow != null && mPopupWindow.isShowing()) {
                        mPopupWindow.dismiss();
                    }
                }
            }

            @Override
            public void scrollBottom() {

                if (CommonTool.isFirstScroll() && !noMore) {
                    pageNum++;
                    getExchangedata();
                }
            }
        });
        adapter.setItemClickListener(new ClearWeedExchangeAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                Intent intent = new Intent(MainHomeActivity.this, ClearWeedDetailActivity.class);
                intent.putExtra("id", clearWeedGoodList.get(position).getId());
                startActivity(intent);
            }
        });
    }

    @Override
    public void onClick(View view) {

        Intent intent = new Intent(context, MainActivity.class);
        switch (view.getId()) {
            case R.id.home_bottom_tab2://弹窗
            case R.id.meibiShop://线上超市
                intent.putExtra("index", 1);
                startActivity(intent);
                break;
            case R.id.home_bottom_tab4:
            case R.id.bolivarShop://豆豆兑换
                intent.putExtra("index", 3);
                startActivity(intent);
                break;
            case R.id.home_bottom_tab5:
            case R.id.ll_offline_shop:  //团购秒杀
                showShortToast("此功能即将上线，敬请期待！");
//                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
//                    intent.putExtra("index", 4);
//                    startActivity(intent);
//                } else {
//                    startAct(LoginActivity.class);
//                }
                break;
            case R.id.home_bottom_tab6:
            case R.id.tv_persion://个人中心
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    intent.putExtra("index", 5);
                    startActivity(intent);
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.home_bottom_tab3:
            case R.id.llUpGift://线下超市商家
                intent.putExtra("index", 2);
                startActivity(intent);
                break;
            case R.id.iv_home_newstore:    //商家中心
                startAct(SellerCenterActivity.class);
                break;
            case R.id.iv_home_qr:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    AndPermission.with(context)
                            .requestCode(100)
                            .permission(Permission.CAMERA)
                            .callback(new PermissionListener() {
                                @Override
                                public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                                    //跳到扫描二维码页面
                                    Intent payIntent = new Intent(context, CaptureActivity.class);
//                                    Intent payIntent = new Intent(context, QrTwoActivity.class);
                                    //startActivity(intent);
                                    //跳液面需要返回一个结果
                                    startActivityForResult(payIntent, MAINHOMEPAYMONEY);
                                }

                                @Override
                                public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {

                                }
                            })
                            .rationale(new RationaleListener() {
                                @Override
                                public void showRequestPermissionRationale(int i, Rationale rationale) {
                                    rationale.resume();
                                }
                            })
                            .start();
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.iv_home_newuser:
                startAct(NewTipsActivity.class);
                break;
            case R.id.tvAd:
                startAct(SystemMessageActivity.class);
                break;
            case R.id.tv_home_servicer:
                if (CommonTool.checkApkExist(MainHomeActivity.this, "com.tencent.mobileqq")) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                            "mqqwpa://im/chat?chat_type=wpa&uin=" + Constants.QQ_NUM + "&version=1")));
                } else {
                    showShortToast("未安装QQ");
                }

                break;
            case R.id.tv_cart:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    startAct(ShoppingCartActivity.class);
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.et_home_newSearchContent:
                startAct(HomeSearchActivity.class);
                break;
            case R.id.home_bottom_tab1:
                if (mPopupWindow != null && mPopupWindow.isShowing()) {
                    mPopupWindow.dismiss();
                    mMyScrollView.fullScroll(View.FOCUS_UP);
                }
                break;
            case R.id.home_top_search:
                startAct(ClearWeedSearchActivity.class);
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(MyApplication.getInstance().getUserId())) {
            getUserInfo();
        }
    }

    /**
     * 是否需要更新
     */
    int version = 0;
    HttpURLConnection conn = null;

    private void isExists() {
        version = Integer.parseInt(MyApplication.getInstance().getMinVersion()) + 1;
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url = null;
                try {
                    url = new URL(Url.APK_URL + version + Url.APK_URL_NAME);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.connect();
                    if (conn.getResponseCode() == 200) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                downFile2();
                            }
                        });
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                finish();
                return true;
            } else {
                return false;
            }
        }
    };

    private void downFile(final String downUrl, String desc) {
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_version, null);
        ImageView iv_Cancel = (ImageView) view.findViewById(R.id.iv_Cancel);
        TextView tv_dsc = (TextView) view.findViewById(R.id.tv_dsc);
        TextView tv_ok = (TextView) view.findViewById(R.id.tv_ok);
        adb.setView(view);
        if (!TextUtils.isEmpty(desc)) {
            tv_dsc.setText(desc);
        } else {
            tv_dsc.setText("发现新版本，请尽快更新");
        }
        dialog = adb.create();
        dialog.setOnKeyListener(keylistener);
        dialog.setCanceledOnTouchOutside(false);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                System.exit(0);
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                downLoadApk(downUrl);
            }
        });


        dialog.show();
    }

    private void downFile2() {
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_version, null);
        ImageView iv_Cancel = (ImageView) view.findViewById(R.id.iv_Cancel);
        TextView tv_dsc = (TextView) view.findViewById(R.id.tv_dsc);
        TextView tv_ok = (TextView) view.findViewById(R.id.tv_ok);
        adb.setView(view);
        tv_dsc.setText("发现新版本，请尽快更新");
        dialog = adb.create();
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setOnKeyListener(keylistener);
        dialog.setCanceledOnTouchOutside(false);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                System.exit(0);
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                downLoadApk2();
            }
        });
        dialog.show();
    }

    private void downLoadApk2() {
        final ProgressDialog pd; //进度条对话框
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setProgress(1000);
        pd.setMessage("正在下载更新");
        pd.setOnKeyListener(keylistener);
        pd.setCanceledOnTouchOutside(false);
        pd.setProgressNumberFormat("%1d M/%2d M");
        pd.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = CommonTool.getFileFromServer(Url.APK_URL + version + Url.APK_URL_NAME, pd);

                    installApk(file);
                    pd.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * 下载APK
     *
     * @param downUrl
     */
    private void downLoadApk(final String downUrl) {
        final ProgressDialog pd; //进度条对话框
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setProgress(1000);
        pd.setMessage("正在下载更新");
        pd.setOnKeyListener(keylistener);
        pd.setCanceledOnTouchOutside(false);
        pd.setProgressNumberFormat("%1d M/%2d M");
        pd.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = CommonTool.getFileFromServer(downUrl, pd);
                    installApk(file);
                    pd.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //安装apk
    protected void installApk(File file) {
        if (file != null) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                Uri apkUri = FileProvider.getUriForFile(context, context.getResources().getString(R.string.authorities), file);//在AndroidManifest中的android:authorities值
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                context.startActivity(install);
            } else {
                Intent intent = new Intent();
                //执行动作
                intent.setAction(Intent.ACTION_VIEW);
                //执行的数据类型
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String text = data.getStringExtra("text");
            String[] split = text.split("\\|\\|");
            /*if (split.length == 5 && ("1".equals(split[0]) || "2".equals(split[0])) && split[1].length() == 20
                    && DataUtil.isDouble(split[2]) && DataUtil.isGoodJson(split[3])) {
                Intent intent = new Intent(context, QrOrderActivity.class);
                intent.putExtra("codeinfo", text);
                startActivity(intent);
            } else*/
            if ("2".equals(split[0]) && split[1].length() == 20 && ("2".equals(split[2]) || "3".equals(split[2]))
                    && DataUtil.isDouble(split[3]) && DataUtil.isDouble(split[4])) {
                Intent mIntent = new Intent(UiUtils.getContext(), PayMoneyActivity.class);
                mIntent.putExtra("secret", split[5]);
                startActivity(mIntent);
            }/* else if ("3".equals(split[0])) {
                Intent intent = new Intent(context, RewardCoinDetailActivity.class);
                intent.putExtra("gid", split[1]);
                startActivity(intent);
            }*/ else {
                showShortToast("无法识别该二维码");
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            MyApplication.getInstance().sharedPrefrences.edit().putString("beautifulcredentials", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardcoincredentials", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("MDChangecredentials", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("OffLinecredentials", "").commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 双击退出程序
     */
    long firstTime = 0;

    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime < 2000) {
            super.onBackPressed();
        } else {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            firstTime = System.currentTimeMillis();
        }
    }

}
